//
//  YTNewFlashController.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/7/9.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "YTNewFlashController.h"
#import "YTNFDayView.h"
#import "YTNewFlashCell.h"
#import "YTNewFlashViewModel.h"
#import "YTShareViewController.h"

NSString *newFlashCellID = @"newFlashCellID";
@interface YTNewFlashController ()

@property(nonatomic ,strong)YTNFDayView *dayView; // 日期视图

@property (assign, nonatomic) BOOL isExpand; //是否展开
@property (strong, nonatomic) NSIndexPath *selectedIndexPath;//展开的cell的下标

@property(nonatomic ,strong)YTNewFlashViewModel *viewModel;

@end

@implementation YTNewFlashController

- (YTNewFlashViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YTNewFlashViewModel alloc] init];
    }
    return _viewModel;
}

#pragma mark: - setupTableView
- (void)setupTableView
{
    if (!self.dayView) {
        self.dayView = [YTNFDayView dayViewWithFrame:CGRectMake(0, kNavbarHeight, kScreenWidth, 28)];
    }
    [super setupTableView];
    
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.dayView.frame),
                                      kScreenWidth, self.view.bounds.size.height - self.dayView.bounds.size.height - self.tabBarController.tabBar.bounds.size.height);
    
    [self.view insertSubview:self.dayView aboveSubview:self.tableView];
    
    // 注册可重用cell
    [self.tableView registerNib:[UINib nibWithNibName:@"YTNewFlashCell" bundle:nil]
                            forCellReuseIdentifier:newFlashCellID];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    YTRefreshHeader *header = [YTRefreshHeader headerWithRefreshingBlock:^{
        [self loadDataWithPullup:NO];
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadDataWithPullup:YES];
    }];
    
    self.tableView.mj_header = header;
    self.tableView.mj_footer = footer;
    [footer setTitle:@"没有更多了哦～" forState:MJRefreshStateNoMoreData];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    
    [self.tableView.mj_header beginRefreshing];
    header.state = MJRefreshStatePulling;
    
    self.tableView.backgroundColor = [UIColor colorWithHex:@"f1f2f2"];
}

#pragma mark: - 加载数据
- (void)loadDataWithPullup:(BOOL)pullup
{
    [self.viewModel loadNewFlashListWithPullup:pullup
                                    completion:^(BOOL isSucc, BOOL shouldReflash)
    {
        if (!isSucc) {
            [self.view showTipWithTipStr:@"网络不给力..."];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            return ;
        }
        
        // 成功
        if (isSucc && shouldReflash) {
            [self.tableView reloadData];
            self.dayView.date = self.viewModel.model.list.date;
            pullup ? [self.tableView.mj_footer endRefreshing] : [self.tableView.mj_header endRefreshing];
        }else{
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}

- (void)setupNav
{
    [super setupNav];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"快讯"
                                                                            style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(leftBtnClick)];
    
    
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor blackColor]];
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} forState:UIControlStateNormal];
    
    [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:171.0f/255.0f green:126.0f/255 blue:128.0f/255.0f alpha:1]];
    
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationEnterBackground)
                                                 name: UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(showPushDetailVC:)
                                               name:kNewFlashPushNotificationName
                                             object:nil];
    
    [self.navigationController.navigationBar setBarTintColor:UIColor.whiteColor];
    
}

#pragma mark: - 消息推送 通知
- (void)showPushDetailVC:(NSNotification *)n
{
    BOOL isArticlePush = [n.userInfo[@"push_isArticle_type"] boolValue];
    NSString *ID = n.userInfo[@"news_id"];
    UIViewController *detailVC = isArticlePush ? [[YTHomeDetailController alloc] init] : [YTDetailNewController controller];
    isArticlePush ? [(YTHomeDetailController *)detailVC setID:ID] : [(YTDetailNewController *)detailVC setID:ID];
    [self.navigationController pushViewController:detailVC animated:true];

}

- (void)applicationEnterBackground
{
    if ([UIViewController isCurrentViewControllerVisible:self])
    {
        [[NSUserDefaults standardUserDefaults] setObject:kNewFlashPushNotificationName forKey:YTPushNotificationName];
    }

}

- (void)dealloc
{
    [NSNotificationCenter.defaultCenter removeObserver:self
                                                  name:UIApplicationDidEnterBackgroundNotification
                                                object:nil];
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 统计页面
    [MobClick beginLogPageView:@"快讯首页"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 统计页面
    [MobClick endLogPageView:@"快讯首页"];
}
#pragma mark: - 导航栏左边 按钮点击
- (void)leftBtnClick
{
    
}

#pragma mark: - table view dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.viewModel.model.list.lives.count;//self.viewModel.model.;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YTNewFlashCell *cell = [tableView dequeueReusableCellWithIdentifier:newFlashCellID
                                                           forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.tag = indexPath.row;
    
    cell.model = self.viewModel.model.list.lives[indexPath.row];
    
    __weak typeof(self) WeakSelf = self;

    cell.changeLayout = ^(NSInteger row) {
        
        if (!self.viewModel.model.list.lives[row]) {
            return ;
        }
        
        YTShareViewController *shareVC = [[YTShareViewController alloc] init];
        shareVC.model = self.viewModel.model.list.lives[row];
        
        [self presentViewController:shareVC animated:true completion:nil];

        
    };
    
    // 需要登录
    cell.shouldLogin = ^{
        YTLoginViewController *logVC = [[YTLoginViewController alloc] init];
        [WeakSelf.navigationController pushViewController:logVC animated:true];
    };
    
    cell.reloadView = ^(NSInteger row) {
        [WeakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    };
    
        return cell;
}


@end
